<template>
    <ul class="list">
      <li
        class="item" v-for="key of letter"
        :key="key"
        :ref="key"
        @click="handLetterClick"
        @touchstart.prevent="handTouchStart"
        @touchmove="handTouchMove"
        @touchend="handTouchEnd"
      >{{key}}</li>
    </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  data () {
    return {
      touchStart: false,
      letters: [],
      startY: 0,
      timer: 0
    }
  },
  props: {
    cities: Object
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handTouchStart () {
      this.touchStart = true
    },
    handTouchMove (e) {
      if (!this.touchStart) {
        return
      }
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const touchY = e.touches[0].clientY - 79
        const index = Math.floor((touchY - this.startY) / 20)
        if (index >= 0 && index <= this.letters.length) {
          this.$emit('change', this.letters[index])
        }
      }, 16)
    },
    handTouchEnd () {
      this.touchStart = false
    }
  },
  computed: {
    letter () {
      const letters = this.letters
      for (let i in this.cities) {
        letters.push(i)
      }
      return this.letters
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
